const { load, save, STORAGE_KEYS } = require('./storage.js')

function ensureSeedData() {
  const seeded = load(STORAGE_KEYS.cases)
  if (seeded && Array.isArray(seeded)) return seeded
  
  const demo = [
    {
      id: 'C2024-001',
      title: '张三与李四合同纠纷案件',
      type: 'civil',
      caseNumber: 'C2024-001',
      description: '原告张三与被告李四于2023年1月5日签订《房屋租赁合同》，约定被告将位于北京市朝阳区的一处房产出租给原告，租期2年，月租金12000元。原告按约定支付了押金24000元及首期租金12000元，但被告未按合同约定交付房屋，且拒绝退还押金和租金。经多次协商未果，原告决定通过法律途径解决。',
      client: {
        name: '张三',
        phone: '13812345678',
        address: '北京市朝阳区建国路88号',
        notes: '客户备注信息'
      },
      userId: 'user001',
      createTime: '2023-10-15',
      updateTime: '2023-10-15',
      evidence: [
        { name: '房屋租赁合同.pdf', size: '2.4 MB' },
        { name: '房屋照片.jpg', size: '1.2 MB' },
        { name: '付款凭证.docx', size: '865 KB' }
      ]
    },
    {
      id: 'C2024-002',
      title: '王五涉嫌故意伤害案件',
      type: 'criminal',
      caseNumber: 'C2024-002',
      description: '被告人王五因与邻居发生争执，涉嫌故意伤害他人身体，造成轻伤后果。案件已进入审查起诉阶段。',
      client: {
        name: '王五',
        phone: '13912345678',
        address: '北京市海淀区中关村大街1号',
        notes: '家属委托'
      },
      userId: 'user001',
      createTime: '2023-10-12',
      updateTime: '2023-10-12',
      evidence: [
        { name: '伤情鉴定书.pdf', size: '1.8 MB' },
        { name: '现场照片.jpg', size: '2.1 MB' }
      ]
    },
    {
      id: 'C2024-003',
      title: '赵六与某局行政诉讼案件',
      type: 'admin',
      caseNumber: 'C2024-003',
      description: '原告赵六不服某局作出的行政处罚决定，认为该决定事实不清、程序违法，请求法院撤销该行政处罚决定。',
      client: {
        name: '赵六',
        phone: '13712345678',
        address: '北京市西城区金融街1号',
        notes: '企业法人代表'
      },
      userId: 'user001',
      createTime: '2023-10-10',
      updateTime: '2023-10-10',
      evidence: [
        { name: '行政处罚决定书.pdf', size: '1.5 MB' },
        { name: '行政复议申请书.docx', size: '1.2 MB' }
      ]
    }
  ]
  
  save(STORAGE_KEYS.cases, demo)
  return demo
}

function getCasesByUser(userId) {
  const allCases = ensureSeedData()
  return allCases.filter(caseItem => caseItem.userId === userId)
}

function getCaseById(id) {
  const allCases = ensureSeedData()
  return allCases.find(caseItem => caseItem.id === id) || null
}

function createCase(caseData) {
  const allCases = ensureSeedData()
  allCases.push(caseData)
  save(STORAGE_KEYS.cases, allCases)
  return caseData
}

function updateCase(caseData) {
  const allCases = ensureSeedData()
  const index = allCases.findIndex(caseItem => caseItem.id === caseData.id)
  if (index !== -1) {
    allCases[index] = { ...allCases[index], ...caseData, updateTime: new Date().toISOString().split('T')[0] }
    save(STORAGE_KEYS.cases, allCases)
    return allCases[index]
  }
  return null
}

function deleteCase(caseId) {
  const allCases = ensureSeedData()
  const filteredCases = allCases.filter(caseItem => caseItem.id !== caseId)
  save(STORAGE_KEYS.cases, filteredCases)
  return true
}

function shareCaseToPhones(caseId, phones) {
  const shares = load(STORAGE_KEYS.shares, {})
  const set = new Set(shares[caseId] || [])
  phones.forEach(p => { if (p) set.add(p) })
  shares[caseId] = Array.from(set)
  save(STORAGE_KEYS.shares, shares)
  return shares[caseId]
}

function getShares(caseId) {
  const shares = load(STORAGE_KEYS.shares, {})
  return shares[caseId] || []
}

function canAccessCaseByPhone(caseId, phone) {
  if (!caseId || !phone) return false
  const target = getCaseById(caseId)
  if (!target) return false
  const inPeople = (target.people || []).some(p => (p.phone || '') === phone)
  if (inPeople) return true
  const shared = getShares(caseId)
  return shared.includes(phone)
}

module.exports = {
  getCasesByUser,
  getCaseById,
  createCase,
  updateCase,
  deleteCase,
  shareCaseToPhones,
  getShares,
  canAccessCaseByPhone
}
